""":cvar
公众号：python研究者
作者：辰哥
"""


import requests
import json
import time
import os
#下载图片
def download_img(img_name,img_url):
    dir = str(time.strftime('%y%m%d', time.localtime()))
    dir_path = "/"+dir
    # 判断文件夹是否存在
    if not os.path.exists(dir_path):
        os.mkdir(dir_path)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'
    }
    r = requests.get(img_url, headers=headers, stream=True)
    if r.status_code == 200:
        # 截取图片文件名
        with open(dir_path+"/"+img_name+".jpg", 'wb') as f:
            f.write(r.content)

#下载视频
def download_mp4(mp4_name,mp4_url):
    dir = str(time.strftime('%y%m%d', time.localtime()))
    dir_path = "/"+dir
    # 判断文件夹是否存在
    if not os.path.exists(dir_path):
        os.mkdir(dir_path)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'
    }
    r = requests.get(mp4_url, headers=headers, stream=True)
    if r.status_code == 200:
        # 截取图片文件名
        with open(dir_path+"/"+mp4_name+".mp4", 'wb') as f:
            f.write(r.content)

headers = {
    'content-type':'application/json',
    'cookie':'自己的cookie',
}
s = json.dumps({
    "keyword": "民谣",
    "pcursor": "",
    "ussid": ""

})
url = 'https://wxmini-api.uyouqu.com/rest/wd/search/feed'
r = requests.post(url, data=s,headers=headers).json()
feeds = r['feeds']
for i in feeds:
    mp4_url = i['mainMvUrls'][0]['url']
    userName = i['userName']
    pic_url = i['coverUrls'][0]['url']
    caption = i['caption']
    #开始下载图片
    download_img(caption,pic_url)
    #开始下载视频
    download_mp4(caption,mp4_url)
    print("mp4_url", mp4_url)
    print("userName", userName)
    print("pic_url", pic_url)
    print("caption", caption)
    print("------------")